//
//  SFTabBarViewController.swift
//  SFWeiboPro
//
//  Created by happy on 2017/9/6.
//  Copyright © 2017年 happy. All rights reserved.
//

import UIKit

class SFTabBarViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        setupChildControllers()
        
        setupComposeButton()
        
        setupNewfeature()
        
        delegate = self
        
        print("statusBar = \(UIApplication.shared.statusBarFrame)")
        print("tabbar = \(tabBar.bounds)")
        
        UIApplication.shared.statusBarStyle = .default
        
        NotificationCenter.default.addObserver(self, selector: #selector(userLogin), name: NSNotification.Name(rawValue: SFUserLoginNotification), object: nil)
    }
    
    //设置设备的旋转方向
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }
    
    deinit {
        //移除通知
        NotificationCenter.default.removeObserver(self)
    }
    
    @objc func userLogin(n: Notification) {
        print("\(n)")
        
        let nav = UINavigationController(rootViewController: SFOAuthViewController())
        
        present(nav, animated: true, completion: nil)
    }
    
    @objc func composeStatus() {
        
        print("发布日志")
    }
    
    lazy var composeButton: UIButton = UIButton.yw_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")

}

// MARK: 设置新版本
extension SFTabBarViewController {
    
    func setupNewfeature() {
        
        let versionView = isNewVersion ? SFNewfeatureView.newfeatureView() : SFWelcomView.welcomView()
        
//        versionView.frame = view.bounds
        
        view.addSubview(versionView)
        
    }
    
    private var isNewVersion: Bool {
        
        print(Bundle.main.infoDictionary ?? [:])
        
        //当前版本号
        let currentVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
        
        //获取沙盒的版本号
        let path: String = ("version" as NSString).yw_appendDocumentDir()
        let sandBoxVersion = try? String(contentsOfFile: path)
        
        //保存当前版本号
        try? currentVersion.write(toFile: path, atomically: true, encoding: .utf8)
        
        return currentVersion != sandBoxVersion
//        return currentVersion == sandBoxVersion
    }
}

extension SFTabBarViewController: UITabBarControllerDelegate {
    
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        
        print("切换到\(viewController)")
        
        if selectedIndex == 0 && childViewControllers.index(of: viewController) == selectedIndex {
            
            print("再次点击首页")
            
            let nav = childViewControllers[0] as! SFNavigationController
            let vc = nav.childViewControllers[0] as! SFHomeViewController
            
            vc.tableView?.setContentOffset(CGPoint(x:0, y: -64), animated: true)
            //刷新数据
            vc.loadData()
        }
        
        return true
    }
    
}

// extension 类似于 OC 中的 分类, 在 swift 中还可以用来切分代码块
// 可以把相近功能的函数,放在一个 extension 中
// 便于代码维护
// 注意: 和OC的分类一样, extension中不能定义属性
extension SFTabBarViewController {
    
    //添加发布按钮
    func setupComposeButton() {
        tabBar.addSubview(composeButton)
        
        let count = CGFloat(childViewControllers.count)
        let width = tabBar.bounds.width / count - 1
        
        composeButton.frame = tabBar.bounds.insetBy(dx: 2 * width, dy: 0)
        
        composeButton.addTarget(self, action:#selector(composeStatus), for: .touchUpInside)
    }
    
    func setupChildControllers(){
        
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath = (docDir as NSString).appendingPathComponent("main1.json")
        
        var data = NSData(contentsOfFile: jsonPath)
        
        if data == nil {
            let path = Bundle.main.path(forResource: "main", ofType: "json")
            data = NSData(contentsOfFile: path!)

        }

        guard let array = try? JSONSerialization.jsonObject(with: (data! as NSData) as Data, options: []) as? [[String: AnyObject]]
            else {
            return
        }
//        let array = [
//            ["clsName": "SFHomeViewController", "title": "首页", "imageName": "home",
//                "visitorInfo": ["imageName": "", "message": "关注一些人,回这里看看有什么惊喜,人生得意须尽欢,莫使金樽空对月"]
//            ],
//            ["clsName": "SFDiscoverViewController", "title": "发现", "imageName": "discover",
//                "visitorInfo": ["imageName": "visitordiscover_image_message", "message": "登录后,别人评论你的微博,发给你的消息,都会在这里收到通知"]
//             ],
//            ["clsName": "UIViewController"],
//            ["clsName": "SFMessageViewController", "title": "消息", "imageName": "message_center",
//             "visitorInfo": ["imageName": "visitordiscover_image_message", "message": "登录后,最新最潮微博尽在掌握,不再会与实时潮流擦肩而过"]
//             ],
//            ["clsName": "SFPodfileViewController", "title": "我的", "imageName": "profile",
//             "visitorInfo": ["imageName": "visitordiscover_image_profile", "message": "登录后,你的微博相册和个人资料都会显示在这里,展示给别人"]
//             ]
//        ]
        
        //将数据写入桌面,仅仅是测试数据是否正确
//        (array as NSArray).write(toFile: "/Users/happy/Desktop/demo.plist", atomically: true)
        
        //数组序列化
//        let data = try! JSONSerialization.data(withJSONObject: array, options: [.prettyPrinted])
//        (data as NSData).write(toFile: "/Users/happy/Desktop/demo.json", atomically: true)
        
        var arrayM = [UIViewController]()
        
        for dict in array! {
            arrayM.append(controller(dict: dict as [String : AnyObject]))
        }
        
        viewControllers = arrayM
    }
    
    //使用字典创建一个子控制器
    // - parameter dict : [clsName, title, imageName]
    private func controller(dict: [String: AnyObject]) -> UIViewController{
        
        // 1.获取字典内容
        guard let clsName = dict["clsName"] as? String,
            let title = dict["title"] as? String,
            let imageName = dict["imageName"] as? String,
            let cls = NSClassFromString(Bundle.main.nameSpace + "." + clsName) as? SFBaseViewController.Type,
            let visitorInfo = dict["visitorInfo"] as? [String: String]
            else {
                return UIViewController()
        }
        
        // 2.创建视图控制器
        let vc = cls.init()
        
        //设置标题
        vc.title = title
        
        //设置标题的属性
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.orange], for: .highlighted)
        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 12)], for: UIControlState(rawValue: 0))
        
        //设置图片
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
        
        vc.visitorInfoDict = visitorInfo
        
        let nav = SFNavigationController(rootViewController: vc)
        
        return nav
        
    }
    
}
